#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WORD_NUM 10
#define MAX_WORD_LENGTH 30

// 比较函数：按照最后一个字母开始逐步向前比较
int compare_words(const char* word1, const char* word2) {
    int len1 = strlen(word1);
    int len2 = strlen(word2);

    // 从最后一个字符开始逐步向前比较
    while (len1 > 0 && len2 > 0) {
        char c1 = word1[len1 - 1];
        char c2 = word2[len2 - 1];
        if (c1 != c2) {
            return c1 - c2; // 字符不同直接返回比较结果
        }
        --len1;
        --len2;
    }

    // 如果所有字符都相等，短的字符串优先
    return len1 - len2;
}

void words_sort(char* words_ptr[WORD_NUM], int length) {
    int left = 0, right = length - 1;
    while (left <= right) {
        int mini = left;
        for (int i = left + 1; i <= right; ++i) {
            if (compare_words(words_ptr[i], words_ptr[mini]) < 0)
                mini = i;
        }
        char* tmp = words_ptr[mini];
        words_ptr[mini] = words_ptr[left];
        words_ptr[left] = tmp;
        ++left;
    }
}

int main() {
    // 使用字符串常量初始化
    char words[WORD_NUM][MAX_WORD_LENGTH] = { "Apple", "Banana", "Cherry", "Grape", "Orange",
                "Mango", "Pineapple", "Strawberry", "Watermelon", "Peach" };

    char* words_ptr[WORD_NUM];

    for (int i = 0; i < WORD_NUM; i++) {
        words_ptr[i] = words[i]; // 将每一行的地址赋值给 words_ptr
    }

    words_sort(words_ptr, WORD_NUM);

    printf("Sorted words:\n");
    for (int i = 0; i < WORD_NUM; ++i)
        printf("%s\n", words_ptr[i]);

    return 0;
}
